package com.yh.correct.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.yh.common.utils.ExcelUtil;
import com.yh.common.utils.IDUtils;
import com.yh.correct.model.Accomplice;
import com.yh.correct.model.CorrectedPerson;
import com.yh.correct.model.FileAttachments;
import com.yh.correct.model.FormModel;
import com.yh.correct.model.JudicialDeptment;
import com.yh.correct.model.Page;
import com.yh.correct.model.ResultData;
import com.yh.correct.model.SocialRelations;
import com.yh.correct.service.ICorrectedPersonService;

/**
 * 作者:王登科 创建时间:2017-03-08 描述:矫正人员控制层
 */
@RestController
@RequestMapping("/correctedPerson")
public class CorrectedPersonController {
	/**
	 * log4j日志
	 */
	private static Logger logger = Logger.getLogger(CorrectedPersonController.class);
	/**
	 * 注入service
	 */
	@Autowired
	private ICorrectedPersonService correctedPersonService;

	@Value("${saveDir}")
	private String saveDir;
	@Value("${photoPath}")
	private String dir;
	/**
	 * 分页+动态条件查询矫正人员
	 */
	@RequestMapping(value = "/findList")
	public Page findCorrectedPersonList(int curPageNum, int pageSize, CorrectedPerson correctedPerson, String birth,
			String birth1) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("curPageNum", curPageNum);
		map.put("pageSize", pageSize);
		map.put("correctedPerson", correctedPerson);
		if(!Objects.equals(birth.trim(), "") && !Objects.equals(birth1.trim(), "")){
			long b=Long.valueOf(birth.replaceAll("[-\\s:]", ""));
			long b1=Long.valueOf(birth1.replaceAll("[-\\s:]", ""));
			if(b>b1){
				birth=null;
				birth1=null;
			}
		}
		map.put("birth", birth);
		map.put("birth1", birth1);
		Page page=new Page();
		try {
			page = correctedPersonService.getCorrectedPersonByPage(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// logger.debug("page:" + page.getResult().size());
		return page;
	}
	/**
	 * 编辑矫正人员
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit(CorrectedPerson correctedPerson){
		logger.debug(correctedPerson);
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			CorrectedPerson cp=correctedPersonService.getCorrectedPerson(correctedPerson);
			map.put("data", cp);
			map.put("str1", correctedPersonService.findType());
			map.put("str2", correctedPersonService.findCrimeTypes());
			map.put("str3", correctedPersonService.findSentenceDate());
		}catch(Exception e){
			e.printStackTrace();
		}
		return new ModelAndView("statisticalReports/correctedPersonEdit",map);
	}
	/**
	 * 修改矫正人员
	 */
	@RequestMapping(value = "/update")
	public ResultData update(@Valid CorrectedPerson correctedPerson) {
		//logger.debug(correctedPerson);
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("correctedPerson", correctedPerson);
			correctedPersonService.updateCorrectedPerson(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResultData();
	}
	/**
	 * 跳转到增加页面
	 */
	@RequestMapping(value = "/preAdd")
	public ModelAndView preAdd() {
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("judicialDeptment", correctedPersonService.getAllUnit());
		logger.debug(condition);
		return new ModelAndView("object_receive/selfreceive_add", condition);
	}
	/**
	 * 增加矫正人员
	 */
	@RequestMapping(value = "/addAll")
	public ResultData submitUserList_2(FormModel fm, MultipartFile file1, MultipartFile file2, MultipartFile file3,
			MultipartFile file4) throws Exception {
		CorrectedPerson correctedperson = fm.getCorrectedperson();
		List<SocialRelations> socilist = fm.getSocilist();
		List<Accomplice> accolist = fm.getAccolist();
		List<FileAttachments> filelist = fm.getFilelist();
		String fileName1 = file1.getOriginalFilename();
		if (!"".equals(fileName1)) {
			//生成文件名字
			String newName=IDUtils.genImageName()+fileName1.substring(fileName1.lastIndexOf("."));
			//上传文件
			file1.transferTo(new File(dir,newName));
			correctedperson.setPhoto(newName);
		}
		String fileName2 = file2.getOriginalFilename();
		if (!"".equals(fileName2)) {
			file2.transferTo(new File(saveDir, fileName2));
			filelist.get(0).setPath(fileName2);
		}
		String fileName3 = file3.getOriginalFilename();
		if (!"".equals(fileName3)) {
			file3.transferTo(new File(saveDir, fileName3));
			filelist.get(1).setPath(fileName3);
		}
		String fileName4 = file4.getOriginalFilename();
		if (!"".equals(fileName4)) {
			file4.transferTo(new File(saveDir, fileName4));
			filelist.get(2).setPath(fileName4);
		}
		correctedPersonService.addAll(correctedperson, socilist, accolist, filelist);
		ResultData rd = new ResultData();
		rd.setCode(0);
		rd.setMessage("入矫人员插入成功!");
		return rd;
	}
	/**
	 * 按id查询入矫人员信息,跳转到修改页面
	 * @throws Exception
	 */
	@RequestMapping(value = "/getAllEdit", method = RequestMethod.GET)
	public ModelAndView toShowEdit(CorrectedPerson correctedPerson) throws Exception {
		Map<String, Object> map = correctedPersonService.getAll(correctedPerson);
		ModelAndView mv = new ModelAndView("/object_receive/selfreceive_edit");
		map.put("flag", "false");
		mv.addObject("map", map);
		logger.debug(map);
		return mv;
	}
	/**
	 * 修改矫正人员信息
	 * @throws Exception
	 */
	@RequestMapping(value = "/editPer")
	public ResultData editResult(FormModel fm, MultipartFile file1, MultipartFile file2, MultipartFile file3,
			MultipartFile file4) throws Exception {
		CorrectedPerson correctedperson = fm.getCorrectedperson();
		List<SocialRelations> socilist = fm.getSocilist();
		List<Accomplice> accolist = fm.getAccolist();
		List<FileAttachments> filelist = fm.getFilelist();
		//查询数据库中相应的数据
		Map<String, Object> map = correctedPersonService.getAll(correctedperson);
		String oldPhoto=(String)map.get("photo");
		if (!"".equals(file1.getOriginalFilename())) {
			if(oldPhoto==null){
				oldPhoto=IDUtils.genImageName()+file1.getOriginalFilename().substring(file1.getOriginalFilename().lastIndexOf("."));
			}
			file1.transferTo(new File(dir, oldPhoto));
		}
		correctedperson.setPhoto(oldPhoto);
		if(file2!=null){
			String fileName2 = file2.getOriginalFilename();
			if (!"".equals(fileName2)) {
				file2.transferTo(new File(saveDir, fileName2));
				filelist.get(0).setPath(fileName2);
			}else{
				String oldFile=((FileAttachments)((ArrayList)map.get("filelist")).get(0)).getPath();
				filelist.get(0).setPath(oldFile);
			}
		}
		if(file3!=null){
			String fileName3 = file3.getOriginalFilename();
			if (!"".equals(fileName3)) {
				file3.transferTo(new File(saveDir, fileName3));
				filelist.get(1).setPath(fileName3);
			}else{
				String oldFile=((FileAttachments)((ArrayList)map.get("filelist")).get(1)).getPath();
				filelist.get(1).setPath(oldFile);
			}
		}
		if(file4!=null){
			String fileName4 = file4.getOriginalFilename();
			if (!"".equals(fileName4)) {
				file4.transferTo(new File(saveDir, fileName4));
				filelist.get(2).setPath(fileName4);
			}else{
				String oldFile=((FileAttachments)((ArrayList)map.get("filelist")).get(2)).getPath();
				filelist.get(2).setPath(oldFile);
			}
		}
		correctedPersonService.editAll(correctedperson, socilist, accolist, filelist);
		ResultData rd = new ResultData();
		rd.setCode(0);
		rd.setMessage("入矫人员修改成功!");
		return rd;

	}
	/**
	 * 按id查询入矫人员信息,跳转到显示页面
	 * 
	 */
	@RequestMapping(value = "/getAll", method = RequestMethod.GET)
	public ModelAndView toShow(CorrectedPerson correctedPerson) throws Exception {
		Map<String, Object> map = correctedPersonService.getAll(correctedPerson);
		ModelAndView mv = new ModelAndView("/object_receive/selfreceive_check");
		mv.addObject("map", map);
		logger.debug(map);
		return mv;
	}
	/**
	 * 获取所有矫正单位
	 * 
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/allunit")
	public ModelAndView getAllUnit() throws UnsupportedEncodingException{
		List<JudicialDeptment> list=correctedPersonService.getAllUnit();
		Map<String,Object> rsMap2 = new HashMap<String,Object>();
		rsMap2.put("allunit", list);
		return new ModelAndView("selfreceive_add", rsMap2);
	}
    /**
	 * 删除入矫人员信息
	 */
	@RequestMapping("/delAll")
	public ResultData delAll(CorrectedPerson correctedPerson) throws Exception{		
		logger.info("删除违规违纪记录id="+correctedPerson.getId());
		correctedPersonService.delAll(correctedPerson);
		return new ResultData();
	}
	/**
	 * 模糊分页查询
	 * @throws ParseException
	 */
	@RequestMapping("/querylike")
	public Map<String, Object> getLikeByPage(int pageNum, int pageSize, CorrectedPerson correctedPerson, String jname,
			String startdate, String enddate) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("pageNum", pageNum);
		map.put("pageSize", pageSize);
		map.put("correctedPerson", correctedPerson);
		map.put("jname", jname);
		if (startdate != null && !"".equals(startdate)) {
			map.put("j_startdate", startdate);
		}
		if (enddate != null && !"".equals(enddate)) {
			map.put("j_enddate", enddate);
		}
		Page page = null;
		try {
			page = correctedPersonService.getLikeCorrectedPerson(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// logger.debug("分页"+page.getResult().size());
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("page", page);
		condition.put("judicialDeptment", correctedPersonService.getAllUnit());
		return condition;
	}
	/**
	 * 删除矫正人员
	 */
	@RequestMapping(value = "/delete")
	public ResultData delete(CorrectedPerson correctedPerson) throws Exception {
		correctedPersonService.delCorrectedPerson(correctedPerson);
		return new ResultData();
	}
	/**
	 * 批量删除矫正人员
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteBatch")
	public ResultData deleteBatch(@RequestParam("id[]") List<Integer> temp){
		try{
			correctedPersonService.deleteBatch(temp);
		}catch(Exception e){
			e.printStackTrace();
		}
		return new ResultData();
	}
	/**
	 * 导出excel表格
	 */
	@RequestMapping(value = "/exportExcel")
	public String download(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String fileName = "办理入矫人员excel文件";
		// 填充projects数据
		List<Map<String, Object>> projects = createData();
		List<Map<String, Object>> list = createExcelRecord(projects);
		String columnNames[] = { "序号", "矫正单位", "姓名", "性别", "证件号", "刑罚类别", "监管级别","矫正起","矫正止","状态" };// 列名
		String keys[] = { "id","jname","name","sex","papersnum","zx_type","jg_rank","j_startdate","j_enddate","state"};// map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] content = os.toByteArray();
		InputStream is = new ByteArrayInputStream(content);
		// 设置response参数，可以打开下载页面
		response.reset();
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (final IOException e) {
			throw e;
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}
	 private List<Map<String,Object>> createData() {
	    	List<Map<String,Object>> list=correctedPersonService.getAllCorrectedPerson();
	        return list;
	 }
	 private List<Map<String, Object>> createExcelRecord(List<Map<String,Object>> projects) {
	        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
	        Map<String, Object> map = new HashMap<String, Object>();
	        map.put("sheetName", "sheet1");
	        listmap.add(map);
	        Map<String,Object> object=null;
	        for (int j = 0; j < projects.size(); j++) {
	        	object=projects.get(j);
	            Map<String, Object> mapValue = new HashMap<String, Object>();
	            mapValue.put("cid", object.get("id"));
	            mapValue.put("cname", object.get("cname"));
	            mapValue.put("sex", object.get("sex"));
	            mapValue.put("papersnum", object.get("papersnum"));
	            mapValue.put("punish", object.get("punish"));
	            mapValue.put("jg_rank", object.get("jg_rank"));
	            mapValue.put("remark", object.get("remark"));
	            mapValue.put("j_startdate", object.get("j_startdate"));
	            mapValue.put("j_enddate", object.get("j_enddate"));
	            mapValue.put("jname", object.get("jname"));
	            listmap.add(mapValue);
	       }
	        return listmap;
	  }
	    
	/**
	 * 查看矫正人员详情 
	 */
	@RequestMapping("/checkDetail")
	public ModelAndView checkDetail(CorrectedPerson correctedPerson){
		Map<String,Object> map = new HashMap<String,Object>();
		try{
			CorrectedPerson cp = correctedPersonService.getCorrectedPerson(correctedPerson);
			map.put("correctedPerson", cp);
		}catch(Exception e){
			e.printStackTrace();
		}
		return new ModelAndView("statisticalReports/correctedPersonCheck",map);
	}
	/**
	 * 跳转办理入矫页面
	 */
	@RequestMapping("/page")
	public ModelAndView page(){
		return new ModelAndView("/object_receive/selfreceive");
	}
	/**
	 * 矫正人员花名册显示列表
	 */
	@RequestMapping("/showCorrectedPersonList")
	public ModelAndView showMain(){
		return new ModelAndView("statisticalReports/correctedPersonRoster");
	}
	/**
	 * 导出表格
	 */
	@RequestMapping(value="/exportCorrectedPersonExcel")
	public String exportExcel(HttpServletResponse response,int[] ids){
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		try {
			if (ids != null && ids.length>0) {
				for (int id : ids) {
					Map<String, Object> map = correctedPersonService.getCorrectedPersonById(id);
					list.add(map);
				}
			} else {
				list = correctedPersonService.getAllCorrectedPersonnel();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map<String,Object>> list1 = createExcelRecordAgain(list);
		String fileName = "矫正人员列表";
		String columnNames[] = { "序号", "矫正人员", "性别", "出生日期", "执行类别", "原判期刑", "罪行","矫正开始日期","矫正截止日期","矫正单位" };// 列名
		String keys[] = { "id", "name", "sex", "birthday", "zx_type", "yp_date", "charge","j_startdate","j_enddate","jname"};// map中的key
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			ExcelUtil.createWorkBook(list1, keys, columnNames).write(os);
			byte[] content = os.toByteArray();
			InputStream is = new ByteArrayInputStream(content);
			// 设置response参数，可以打开下载页面
			response.reset();
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
			ServletOutputStream out = response.getOutputStream();
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();;
		} finally {
			try{
				if (bis != null)
					bis.close();
				if (bos != null)
					bos.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		return "";
	}
	/**
	 * excel辅助方法
	 */
	private List<Map<String, Object>> createExcelRecordAgain(List<Map<String, Object>> projects) {
		List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("sheetName", "sheet1");  
		listmap.add(map);
		Map<String, Object> object = null;
		for (int j = 0; j < projects.size(); j++) {
			object = projects.get(j);
			Map<String, Object> mapValue = new HashMap<String, Object>();
			mapValue.put("id", j+1);
			mapValue.put("name", object.get("name"));
			mapValue.put("sex", object.get("sex"));
			mapValue.put("birthday", object.get("birthday"));
			mapValue.put("zx_type", object.get("zx_type"));
			mapValue.put("yp_date", object.get("yp_date"));
			mapValue.put("charge", object.get("charge"));
			mapValue.put("j_startdate", object.get("j_startdate"));
			mapValue.put("j_enddate", object.get("j_enddate"));
			mapValue.put("jname", object.get("jname"));
			listmap.add(mapValue);
		}
		return listmap;
	}
}
